package com.libo.server;

import com.libo.bean.Environment;
import com.libo.server.receive.Receive;
import com.libo.server.receive.impl.ReceiveImpl;
import com.libo.server.store.Store;
import com.libo.server.store.impl.StoreImpl;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 服务端启动入口
 */
public class Server {
    public static void main(String[] args) {
        ServerSocket serverSocket = null;
        ExecutorService executorService = null;
        try {
            //创建数据库连接
            executorService = Executors.newFixedThreadPool(10);
            //创建服务器对象
            serverSocket = new ServerSocket(9999);
            System.out.println("服务器启动成功，等待客户端连接。。。");
            while (true) {
                Socket socket = serverSocket.accept();
                System.out.println("客户端{"+socket.getInetAddress()+"}连接成功");
                executorService.submit(()->{
                   //接收数据
                    Receive receive = new ReceiveImpl();
                    List<Environment> environments = receive.receive(socket);
                    environments.forEach(environment -> System.out.println("environment:"+environment));
                    //todo 入库
                    Store store = new StoreImpl();
                    store.store(environments);
                });
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally {
            if (serverSocket != null) {
                try {
                    serverSocket.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
}
